import json
import time
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
import execjs


class Spider():
    def __init__(self):
        self.e_key = '55b3b62613aef1a0'
        self.d_key = '0a1fea31626b3b55'
        self.js_compile = execjs.compile(open('mmz.js',encoding='utf-8').read())

    def gen_req_data(self, req_data):
        encrypt_key = '55b3b62613aef1a0'
        encrypt_iv = '55b3b62613aef1a0'
        aes_encrypt = AES.new(encrypt_key.encode(), AES.MODE_CBC, encrypt_iv.encode())
        pad_16_text = (pad(req_data.encode(), 16))
        base64_encrypt_data = base64.b64encode(aes_encrypt.encrypt(pad_16_text))
        base64_encrypt_data_str = base64_encrypt_data.decode()
        return base64_encrypt_data_str

    def gen_result_data(self, result):
        decrypt_key = '0a1fea31626b3b55'
        decrypt_iv = '0a1fea31626b3b55'
        aes_encrypt = AES.new(decrypt_key.encode(), AES.MODE_CBC, decrypt_iv.encode())
        encrypt_data = aes_encrypt.decrypt(base64.b64decode(result.encode())).decode()
        return encrypt_data

    def main(self):
        timestamp_ms = int(time.time() * 1000)
        req_data = json.dumps({
            "Type": 0,
            "page": 6,
            "expire": timestamp_ms
        })
        # headers = {
        #     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
        # }
        # url = "https://www.maomaozu.com/index/build.json"
        # response = requests.post(url, headers=headers, data=data)
        # res = self.gen_result_data(response.text)
        # return res
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
        }
        url = "https://www.maomaozu.com/index/build.json"
        data = self.js_compile.call('en', self.e_key, req_data)
        response = requests.post(url, headers=headers, data=data).content.decode('gbk')
        result = self.js_compile.call('de', self.d_key, response)
        for i in json.loads(result)['list']:
            print(i)


if __name__ == '__main__':
    spider = Spider()
    spider.main()
